package com.baidu.camera.widget;

import android.content.Context;
import android.content.res.ObbInfo;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.SurfaceTexture;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;

import com.baidu.camera.utils.FileUtils;
import com.baidu.camera.utils.MetricsUtils;
import com.baidu.camera.utils.ToastUtils;
import com.serenegiant.usb.USBMonitor;
import com.serenegiant.usb.UVCCamera;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * Created by JGW-android on 2016/3/10.
 */
public class CaptureImageView extends SurfaceView implements SurfaceHolder.Callback {
    //capture picture related
    private Bitmap catchBitmap;
    private Bitmap tempBitmap;
    private Object lock = new Object();
    private boolean isRemain;

    private UVCCamera uvcCamera;
    private Canvas mCanvas;

    public CaptureImageView(Context context) {
        super(context);
    }

    public CaptureImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        DisplayMetrics metrics = MetricsUtils.winMetrics(context);
        tempBitmap = Bitmap.createBitmap(metrics.widthPixels, metrics.heightPixels, Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(tempBitmap);

        getHolder().addCallback(this);

    }

    public CaptureImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (holder == null) return;
        initCanvas(holder);
        bindCamera();
    }

    //use for getting picture cathe files
    private void initCanvas(SurfaceHolder holder) {
        holder.lockCanvas().setBitmap(tempBitmap);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(mCanvas);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
//        synchronized (lock) {
//            if (!isRemain) {
//                isRemain = true;
//                if (catchBitmap == null) {
//                    catchBitmap = Bitmap.createBitmap(getDrawingCache());
//                } else {
//                    tempBitmap = catchBitmap;
//                }
//                lock.notifyAll();
//            }
//        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (holder == null) return;
        releaseCamera();
    }

    //get picture
//    public Bitmap getBitmap() {
//        catchBitmap = null;
//        synchronized (lock) {
//            isRemain = false;
//            try {
//                lock.wait();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            return tempBitmap;
//        }
//    }

    //bind camera
    public void bindCamera() {
        if (uvcCamera == null) return;
        uvcCamera.setPreviewDisplay(getHolder());
        uvcCamera.startPreview();
    }

    //release camera
    public void releaseCamera() {
        if (uvcCamera == null) return;
        uvcCamera.stopPreview();
        uvcCamera.destroy();
        uvcCamera = null;
    }

    //init camera
    public void initCamera(USBMonitor.UsbControlBlock ctrlBlock) {
        uvcCamera = new UVCCamera();
        uvcCamera.open(ctrlBlock);
    }

//    public Bitmap getBitmap(int width, int height) {
//        if (isAvailable() && width > 0 && height > 0) {
//            return getBitmap(Bitmap.createBitmap(getResources().getDisplayMetrics(),
//                    width, height, Bitmap.Config.ARGB_8888));
//        }
//        return null;
//    }

//    public Bitmap getBitmap() {
//        return getBitmap(getWidth(), getHeight());
//    }

//    public Bitmap getBitmap(Bitmap bitmap) {
//        if (bitmap != null && isAvailable()) {
//            applyUpdate();
//            applyTransformMatrix();
//
//            // This case can happen if the app invokes setSurfaceTexture() before
//            // we are able to create the hardware layer. We can safely initialize
//            // the layer here thanks to the validate() call at the beginning of
//            // this method
//            if (mLayer == null && mUpdateSurface) {
//                getHardwareLayer();
//            }
//
//            if (mLayer != null) {
//                mLayer.copyInto(bitmap);
//            }
//        }
//        return bitmap;
//    }

    public boolean isAvailable() {
        return getHolder() != null;
    }

    public void storeBitmap() {
        if (tempBitmap == null) return;
        try {
            OutputStream os = new FileOutputStream(FileUtils.createImageFile(Environment.getExternalStorageDirectory() + "/img"));
            tempBitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
            os.flush();
            ToastUtils.simpleToast(getContext(), "store successfully");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
